<?php

namespace Aoe\Emulator\Ui;

use Aoe\Emulator\Ifc\Key;
use Aoe\Emulator\Schema\Element\Independent;
use Closure;
use Throwable;

abstract class Item extends Component
{
    protected ?Independent $element;

    public function __construct(
        readonly public Context $context,
        ?Independent      $element
    ){
        parent::__construct($this->context);
        $this->element = $element;
    }
    
    public function render(?array $declarer = null): array
    {
        if (null === $declarer) $declarer = $this->declarer;
        
        if (!$this->element) return $declarer;
        
        if (!isset($declarer[Key::NAME])) $declarer[Key::NAME] = $this->element->name;
        if (!isset($declarer[Key::LABEL])) $declarer[Key::LABEL] = $this->element->label;
        
        return $declarer;
    }

    public static function renderItems(Context $context, array $declarers, Closure $fn): array
    {
        $items    = [];
        try {
            $model = $context->getModel();
        } catch (Throwable) {
            return $items;
        }

        foreach ($declarers as $declarer) {
            // 特殊的表单域
            if (!isset($declarer[Key::NAME])) {
                $items[] = $declarer;
                continue;
            }

            $name = $declarer[Key::NAME];
            if (!$model->hasElement($name)) continue;
            try {
                $items[] = $fn($context, $model->getElement($name), $declarer);
            } catch (Throwable) {}
        }

        return $items;
    }
}